package com.github.catvod.spider;
import android.content.Context;
import android.text.TextUtils;
import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Notify;
import com.github.catvod.utils.Path;
import com.github.catvod.utils.Util;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.ResponseBody;
import com.github.catvod.bean.torrent.*;

public class Taohuazu extends Spider {

    private  String siteUrl = "http://thzr.cc/";//自己加什么也不知道


    private JsonObject extend;
    private HashMap<String,  String> getHeaders() {

        HashMap<String,  String> headers = new HashMap<>();
        headers.put("User-Agent", Util.CHROME);
        return headers;
    }




    private Map<String, String> getHeader() {

        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        return header;
    }



    @Override
    public String homeContent(boolean filter) throws Exception {

        List<Class> classes = new ArrayList<>();
        List<String> typeIds = Arrays.asList("181", "220", "182", "69");
        List<String> typeNames = Arrays.asList("亚洲无", "亚洲有", "欧美无", "国内原创");
        for (int i = 0; i < typeIds.size(); i++) classes.add(new Class(typeIds.get(i), typeNames.get(i)));
        String f = "{}";//自己加什么也不知道
        JSONObject filterConfig = new JSONObject(f);

        return Result.string(classes, filterConfig);
    }



    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        String cateId = extend.get("cateId") == null ? tid : extend.get("cateId");
        String classType = extend.get("class") == null ? "" : extend.get("class");
        String cateUrl = siteUrl + String.format("/forum.php?mod=forumdisplay&fid=%s&filter=typeid&typeid=%s&page=%s",cateId , classType,pg);
        Document doc =Jsoup.parse(OkHttp.string(cateUrl, getHeader()));

        int page = Integer.parseInt(pg), limit = 60, total = 0;
        int count = 500000;
        return Result.get().vod(parseVodListFromDoc(doc)).page(page, count, limit, total).string();
    }



    private List<Vod> parseVodListFromDoc(Document doc) {
        List<Vod> list = new ArrayList<>();
        Elements elements = doc.select("tbody[id^=normalthread_]");
        for (Element e : elements) {
            String vodId = e.selectFirst("tr .icn a").attr("href");
            String vodPic = "";
            String vodName = e.selectFirst("tr th .s.xst").text();
            String vodRemarks = e.selectFirst("tr th em a").text();
            list.add(new Vod(vodId, vodName, vodPic, vodRemarks));
        }
        return list;
    }

    @Override

    public String detailContent(List<String> ids) throws Exception {
        String vodId = ids.get(0);
        Document doc = Jsoup.parse(OkHttp.string(siteUrl + vodId, getHeader()));
        Vod item = new Vod();
        item.setVodId(vodId);
        item.setVodName(doc.selectFirst("#thread_subject").text());
        Map<String, String> sites = new LinkedHashMap<>();
        String sourceName = "气氛搞起来";
        List<String> vodItems = new ArrayList<>();
        String tmpplay=doc.select(".attnm a").attr("href");
        String[] lines = tmpplay.split("aid=");
        String  player = siteUrl+"/forum.php?mod=attachment&aid="+lines[1];

        ResponseBody responseBody=OkHttp.newCall(siteUrl+"/forum.php?mod=attachment&aid="+lines[1]).body();
        assert responseBody != null;
        InputStream rInputStream = responseBody.byteStream();
        // 创建读取字节流的byte数组
        byte[] buffer = new byte[5000];
        int areRead;
        // 创建文件输出流
        FileOutputStream outputStream = new FileOutputStream(getCache());
        // 使用输入流读取字节，在输出到文件
        while ((areRead = rInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, areRead);
        }
        rInputStream.close();
        outputStream.close();
        TorrentFile torrentFile = TorrentFileUtils.resolve(getCache().toString());
        vodItems.add("气氛搞起来" + "$" + torrentFile.getMagnetUri());
        sites.put(sourceName, TextUtils.join("#", vodItems));
        item.setVodPlayFrom(TextUtils.join("$$$", sites.keySet()));
        item.setVodPlayUrl(TextUtils.join("$$$", sites.values()));
        return Result.string(item);
    }


    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        return searchContent(key, "1");
    }

    @Override
    public String searchContent(String key, boolean quick, String pg) throws Exception {
        return searchContent(key, pg);
    }
    private String searchContent(String key, String pg) {
        List<Vod> list = new ArrayList<>();
        return Result.string(list);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {

            return Result.get().url(id).header(getHeader()).string();
    }


    public File getCache() {
        return Path.tv("搞得贼爽.torrent");
    }
}
